<?php
session_start();
   // include function files for this application
   require('dbconnection.php');
   require("page.php");
   // Instantiate the Page class
   //$webPage = new Page();    
   //get form data
   $username=$_POST['username'];
   $passwd=$_POST['passwd'];
   $passwd2=$_POST['passwd2'];

   try
   {
      // check forms filled in
      $filled = true;
      foreach ($_POST as $key => $value)
      {
         if (!isset($key) || ($value == '')) 
            $filled = false;
      } 
      if (!$filled)
      {
         throw new Exception('You have not filled the form out correctly 
          - please try again.');    
      }

      // passwords not the same 
      if ($passwd != $passwd2)
      {
         throw new Exception('The passwords you entered do not match 
                - please try again.');
      }

      // check password length is ok
      if (strlen($passwd)<6 )
      {
         throw new Exception('Your password must be >=6 characters.'
                           .'Please try again.');
      }
   
      // attempt to register
      // connect to db
      $conn = db_connect();
    
      // check if username is unique 
      $select ="SELECT * FROM users WHERE username='$username'";
      $result = mysql_query($select); 
      if (!$result)
         throw new Exception('Could not execute query :'.$select 
		                          . ':' . mysql_error());
      if (mysql_num_rows($result)>0) 
         throw new Exception('That username is taken
                              - go back and choose another one.');

      // if ok, put in dd
      $pw = sha1($passwd);
      $insert = "INSERT INTO users (username,password) VALUES('$username','$pw')";
      $result = mysql_query($insert);
      if (!$result)
         throw new Exception('problem with '. $insert
		                      . ':' . mysql_error());
      // register session variable 
      $_SESSION['username'] = $username;

      // show home page with user menu
      
      print(addHeader('Registration Success:'));
      print("<h2>Registration Success</h2>");
      print("Welcome to Sycamore ".$username);
   }
   catch (Exception $e)
   {
      print(addHeader('Problem with registration details:'));
      print("<h2>Registration Error</h2>");
      print($e->getMessage());
      print(" please <a href=signup.php>Try again</a>");	  
   } 

   // Add the footer to the page
   print(addFooter());
?>
